package com.xxx.base.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.access.vote.RoleHierarchyVoter;
import org.springframework.security.config.core.userdetails.UserDetailsMapFactoryBean;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Map;

@Configuration
@ConfigurationProperties("spring.security")
public class SecurityAutoConfig {

    private Map<String, String> inMemUsers;
    private String roleHierarchy;


    @Bean
    @ConditionalOnMissingBean(type = "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository")
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() throws Exception {
        UserDetailsMapFactoryBean usersFactoryBean = new UserDetailsMapFactoryBean(inMemUsers);
        return new InMemoryUserDetailsManager(usersFactoryBean.getObject());
    }

    @Bean
    public RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy(roleHierarchy);
        return hierarchy;
    }

    @Bean
    public RoleHierarchyVoter roleHierarchyVoter() {
        return new RoleHierarchyVoter(roleHierarchy());
    }

    public Map<String, String> getInMemUsers() {
        return inMemUsers;
    }

    public SecurityAutoConfig setInMemUsers(Map<String, String> inMemUsers) {
        this.inMemUsers = inMemUsers;
        return this;
    }

    public String getRoleHierarchy() {
        return roleHierarchy;
    }

    public SecurityAutoConfig setRoleHierarchy(String roleHierarchy) {
        this.roleHierarchy = roleHierarchy;
        return this;
    }
}
